<?php
class Q_Rule_Upload extends Q_Rule_Abstract {

    public function isValid($value) {
    
        $field = $this->getParam('field');
        $min = $this->getParam('min');
        $max = $this->getParam('max');
        $types = $this->getParam('types');
        if (array_key_exists($field, $_FILES)) {
            $fileinfo = $_FILES[$field];
            $minmatch = true;
            $maxmatch = true;
            $typematch = true;
            if (!$type = self::getMimeType($fileinfo['tmp_name'])) {
                // @todo not wure what else to do here...
                $type = 'application/octet-stream';
            }
            if ($min) {
                $minmatch = ($fileinfo['size'] >= $min);
            }
            if ($max) {
                $maxmatch = ($fileinfo['size'] <= $max);
            }
            if ($types) {
                if (!is_array($types)) $types = (array) $types;
                if (!in_array($type, $types)) $typematch = false;
            }
            return ($minmatch && $maxmatch && $typematch);
        }
        return false;
    
    }
    
    static public function getMimeType($file) {
    
        $mtype = false;
        if (function_exists('mime_content_type')){
            $mtype = mime_content_type($file);
        }
        else if (function_exists('finfo_file')){
            $finfo = finfo_open(FILEINFO_MIME);
            $mtype = finfo_file($finfo, $file);
            finfo_close($finfo);  
        }
        $mtype = preg_replace('~^([^/\s]+/[^/\s;]+).*$~', '\1', $mtype);
        if (!$mtype) {
            throw new Q_Rule_Exception('No way to determine mime type in upload validation rule.');
        }
        return $mtype;
    
    }

}
